<template>
  <div class="">
    <a-modal
      v-model:visible="visible"
      :title="dialogTitle"
      :ok-loading="btnLoading"
      :modal-style="modalStyle"
      :body-style="bodyStyle"
      :mask-closable="false"
      @cancel="dialogCancel"
      @before-ok="dialogBeforeOk"
    >
      <a-form ref="formRef" :model="formModel">
        <a-form-item field="status" label="是否启用">
          <a-switch v-model="formModel.status" :checked-value="1" :unchecked-value="2"/>
        </a-form-item>
        <a-form-item
          field="name"
          label="名称"
          required
          :validate-trigger="['change', 'input']"
          :rules="[
            {
              required: true,
              message: '名称不能为空',
            },
          ]"
        >
          <a-input v-model="formModel.name" placeholder="请输入名称"/>
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="formModel.remark" allow-clear :max-length="{ length: 120, errorOnly: true }" :auto-size="{ minRows: 5,maxRows: 8 }" show-word-limit/>
        </a-form-item>
        <a-form-item field="sort" label="排序">
          <a-input-number v-model="formModel.sorting" :style="{width:'100px'}"/>
        </a-form-item>
        <a-form-item
          field="access_ids"
          label="权限"
          :rules="[
            {
              required: true,
              message: '至少选择一个权限',
            },
            {
              type: 'array',
              minLength: 1,
              message: '至少选择一个权限',
            },
          ]"
        >
          <a-tree
            :checkable="true"
            :check-strictly="checkStrictly"
            v-model:checked-keys="checkedMenuIds"
            :data="treeMenus"
            :field-names="{ children: 'children', title: 'name', key: 'id' }"
            @check="menuCheck"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
  import { ref } from 'vue';

  import useVisible from '@/hooks/visible';
  import { apiInfo, apiSave } from '@/api/admin-role';
  import { apiTreeList as apiMenuTree } from '@/api/admin-menu';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    id: {
      type: [Number, String],
      default: '',
    },
  });
  const emit = defineEmits(['saveCallback']);

  const baseFormModel = () => {
    return {
      id: '',
      created_at: '',
      updated_at: '',
      name: '',
      remark: '',
      access_ids: [],
      sorting: 100,
      status: 1,
    };
  };
  const formRef = ref();
  const formModel = ref(baseFormModel());
  const modalStyle = {
    width: '60%',
    height: '70%',
    maxWidth: '700px',
  };
  const bodyStyle = {
    height: 'calc(100% - 108px)',
    overflow: 'auto',
  };

  const { visible, setVisible } = useVisible(false);
  const dialogTitle = ref();
  const btnLoading = ref(false);

  const checkStrictly = ref(true);
  const checkedMenuIds = ref([]); // 选中的权限菜单
  const treeMenus = ref([]); // 权限菜单

  // 表单重置
  const reset = async () => {
    formModel.value = baseFormModel();
    await formRef.value?.resetFields();
    checkedMenuIds.value = [];
  };
  const fetchData = async (row = {}) => {
    await getMenuTree();

    setVisible(true);
    dialogTitle.value = '新增';
    if (row.id) {
      dialogTitle.value = `编辑ID: ${row.id}`;
    }

    await reset();
    if (row.id) {
      const { data } = await apiInfo({ id: row.id });
      formModel.value = data;
      checkedMenuIds.value = data.access_ids;
    }
  };
  // 提交
  const submit = async (done) => {
    try {
      const ruleRes = await formRef.value?.validate();
      if (!ruleRes) {
        await apiSave(formModel.value);
        done();
        emit('saveCallback');
      } else {
        done(false);
      }
    } catch (err) {
      done(false);
    } finally {
      done(false);
    }
  };
  const getMenuTree = async () => {
    const { data } = await apiMenuTree({status: 1});
    treeMenus.value = data.data;
  };
  // 菜单选择
  const menuCheck = (checkedKeys) => {
    formModel.value.access_ids = checkedKeys;
  };

  const dialogCancel = () => {
    setVisible(false);
    reset();
  };
  const dialogBeforeOk = (done) => {
    submit(done);
  };

  // 暴露方法【给父级调用】
  defineExpose({
    fetchData,
  });
</script>

<style scoped lang="less">

</style>
